package com.ustcinfo.study.mr.xujianan;

import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

/**
 * @author xujn
 * @ClassName: MyWorldCount
 * @Description 统计单词个数
 */
public class MyWorldCount {

    //    map操作       Mapper<keyIn,ValueIn,KeyOut,valueOut>
    private static class MyMapper extends Mapper<Object, Text, Text, IntWritable> {
        private static final IntWritable count = new IntWritable(1);

        @Override
        protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
            String line = value.toString();   //输入文本内容 转为字符串
            String[] arr = line.split(" ");  //空格分割字符串
            for (String anArr : arr) {
                Text word = new Text();
                word.set(anArr);   //字符片段存入
                context.write(word, count);
            }
        }
    }

    // reduce操作
    private static class MyReducer extends Reducer<Text, IntWritable, Text, IntWritable> {
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable v : values) {
                sum += v.get();
            }
            context.write(key, new IntWritable(sum));
        }
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
        Job job = Job.getInstance();
        job.setJobName("sg_word_count");
        // 设置可运行的class对象，hadoop利用这个类来查找包运行它的jar文件，进而找到相关的jar文件
        job.setJarByClass(MyWorldCount.class);

        job.setMapperClass(MyMapper.class);
        job.setCombinerClass(MyReducer.class);
        job.setReducerClass(MyReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);
        // 设置输入输出文件。输出结果路径如果已经存在，hadoop就会报错并拒绝运行作业，以此来防止数据的丢失
        FileInputFormat.addInputPath(job, new Path(args[0]));  //要分析数据文件的路径
        FileOutputFormat.setOutputPath(job, new Path(args[1]));  //输出路径

        // 等待运行作业。hadoop yarn中的resourceManager有一个作业队列，如果作业较多就会等待
        // 参数如果是true表示需要把运行过程打印到控制台
        int status = job.waitForCompletion(true) ? 0 : -1;
        System.exit(status);
    }

}
